var prefix = "/sysContract";

var myPdf = [],myPdfYi = [],oldPdf=[],myPdfItem = {name: '', url: '', id: '',contractType:1,orderId:0}, myDataList = [],oldHT=[0,0]
var remove = (id,number) => {
    if(number==0){
        if (myPdf.find(item => item.id == id + '-0')) {
            //删除这条
            myPdf = myPdf.filter((item) => {
                return !(id + '-0').includes(item.id)
            });
            $('#myUpdataDiv').find('div[myid=' + id + '-0]').remove();
             --oldHT[0]
        }
    }else{
        if (myPdfYi.find(item => item.id == id + '-0')) {
            //删除这条
            myPdfYi = myPdfYi.filter((item) => {
                return !(id + '-0').includes(item.id)
            });
            $('#myUpdataDivYi').find('div[myid=' + id + '-0]').remove();
             --oldHT[1]
        }
    }
    event.stopPropagation();
}
var openPdf = (id) => {
    let myItem = myPdf.find(item => item.id == id + '-0')
    myItem =null==myItem? myPdfYi.find(item => item.id == id + '-0'):myItem
    myItem =null==myItem? oldPdf.find(item => item.id == id + '-0'):myItem
    if (myItem) {
        if(myItem.contractType==0){
            let a= document.createElement("a");
            a.href=`/jzApi/jazUserAunt/userOrderExport?orderId=${myItem?.orderId}`
            a.download="合同.docx"
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            return false;
        }
        let toIndex = layer.open({
            type: 2,
            area: ['80%', '80%'],
            fixed: false, //不固定
            maxmin: true,
            content: myItem.url
        });
    }
}

var openOldPdf = (number) => {
    let toIndex = layer.open({
        type: 2,
        area: ['80%', '80%'],
        fixed: false, //不固定
        maxmin: true,
        content: number==0?$('#oldcontract').val():$('#oldcontractNameYiPath').val()
    });
}

layui.use(['form', 'xmSelect', 'upload', 'laydate'],  ()=> {
    var form = layui.form;
    var layer = layui.layer;
    var upload = layui.upload;
    var xmSelect = layui.xmSelect;
    var laydate = layui.laydate;
    var loading, myDataList1 = [], myDataList2 = [];

    if ($('#orderType').val() == 1 && $('#status').val() == 0 && $('#type').val() == 'edit') {
        //保洁
        $('#mySelect').attr("disabled", true);
        AjaxGet("/jzweb/jazUserOrder/getUserAuntBaoJie", {
            // projectId: $('#projectId').val(),
            // id:$('#dataId').val()
        }).then(response => {
            myDataList = response.data
            //设置select
            $('#mySelect').empty();
            $('#mySelect').append($('<option>', {
                value: '',
                text: '请选择姓名'
            }))
            response.data.forEach(item => {
                $('#mySelect').append($('<option>', {
                    value: item.sysUserid,
                    text: item.name+'-'+item.mobile,
                    selected: item.sysUserid==$('#signingId').val()
                }))
            })
            $('#mySelect').attr("disabled", false);
            form.render('select');
            selectInput($('#mySelect'), 10)
        }).catch(e => {
            layer.msg(e.msg);
        })
        form.on('select(mySelect-filter)', function (data) {
            var value = data.value; // 获得被选中的值
            if (value != "") {
                let item = myDataList.find((itemdata) => itemdata.sysUserid == value)

                //姓名显示
                // myjazSysProjectList
                $('#mobiles').html(`<span>${item.mobile}</span>`)
            } else {
                $('#mobiles').html('<span style="color: rgb(117 117 117);">请先选择姓名</span>')
            }
        });
    }

    if ($('#orderType').val() == 2 && ($('#type').val() == 'edit' || $('#type').val() == 'transferor' ||$('#type').val() == 'renew')) {

        //阿姨
        $('#names').attr("disabled", true);
        AjaxGet("/jzweb/jazUserOrder/getUserAunt", {
            projectId: $('#projectId').val(),
            id:$('#dataId').val()
        }).then(response => {
            myDataList = response.data
            //设置select
            $('#names').empty();
            $('#names').append($('<option>', {
                value: '',
                text: '请选择姓名'
            }))
            response.data.forEach(item => {
                $('#names').append($('<option>', {
                    value: item.sysUserid,
                    text: item.name+'-'+item.mobile,
                    selected: $('#type').val()!='transferor'?item.sysUserid==$('#signingId').val():false
                }))
            })
            $('#names').attr("disabled", $('#type').val()=='renew');
            form.render('select');
            selectInput($('#names'), 10)
        }).catch(e => {
            layer.msg(e.msg);
        })
        form.on('select(names-filter)', function (data) {
            var value = data.value; // 获得被选中的值
            if (value != "") {
                let item = myDataList.find((itemdata) => itemdata.sysUserid == value)
                //姓名显示
                $('#mobiles').val(`${item.mobile}`)
                $('#idNumbers').val(`${item.idNumber}`)
                $('#detailedAddress2').val(`${item.address}`)
                $('#signingId').val(value)
            } else {
                $('#mobiles').val('请先选择姓名')
                $('#idNumbers').val('请先选择姓名')
            }
        });

        $('#mySelect-projectId').attr("disabled", true);
        AjaxGet('/userAunt/seleProject').then(function (response) {
            myDataList = response.data
            //设置select
            $('#mySelect-projectId').empty();
            $('#mySelect-projectId').append($('<option>', {
                value: '',
                text: '请选择订单类型'
            }))
            response.data.forEach(item => {
                $('#mySelect-projectId').append($('<option>', {
                    value: item.id,
                    text: item.name,
                    selected: item.id == $('#projectId').val()
                }))
            })
            $('#mySelect-projectId').attr("disabled", $('#type').val() == 'transferor'||$('#type').val() == 'edit'||$('#type').val()=='renew');
            form.render('select');
            selectInput($('#mySelect-projectId'), 10)
        }).catch(function (error) {
            layer.msg(error.msg)
        })
        if($('#type').val()=='renew'){
            laydate.render({
                elem: '#endTimes',
                rangeLinked: true,
                type: 'datetime',
                min:$('#endTimes').val(),
                done: function (value, date, endDate) {
                   $('#ID-laydate-range-datetime').val($('#oldstartTime').val()+' - '+value)
                }
            });
        }else{
            laydate.render({
                elem: '#ID-laydate-range-datetime',
                rangeLinked: true,
                type: 'datetime',
                range: true,
                min:$('#endTimes').val(),
                done: function (value, date, endDate) {
                    console.log('==')
                }
            });
        }

        //合同回显
        let MYId=0
        if($('#type').val() != 'transferor'){
            let list = $('#pdfList').val()
            list = list ? list.split(',') : []

            for (let i = 0; i < list.length; i++) {
                myPdfItem = {name: '文件' + (i + 1), url: '', id: '',contractType:$('#contractType').val(),orderId:0}

                myPdfItem.url = list[i]
                myPdfItem.id = MYId
                myPdfItem.orderId = $('#dataId').val();
                $('#myUpdataDiv').prepend(`
				<div href="#" class="mybutton upload " myid="${myPdfItem.id+'-0'}" onclick="openPdf(${myPdfItem.id});" > 
					    <img class="upImg" src="/img/pdf.png">
						<span style=" color: #000;   text-align: center; ">
							${myPdfItem.name}</span>
						<input value="${myPdfItem.id}" class="layui-hide"> 
						<a href="#" onclick="remove(${myPdfItem.id},0);"> `+
                    ($('#type').val() == 'edit'? `<img  class="closeUpload" src="/img/close.png" >	`:'')+` </a></div>`)
                myPdfItem.id = MYId + '-0'
                if($('#type').val() == 'edit'){
                    myPdf.push(myPdfItem)
                }else{
                    oldPdf.push(myPdfItem)
                }
                ++MYId;
            }

            let listold = $('#pdfListOld').val()
            listold = listold ? listold.split(',') : []
            oldHT[0]=-1
            for (let i = 0; i < listold.length; i++) {
                myPdfItem = {name: '文件' + (i + 1), url: '', id: '',contractType:$('#contractType').val(),orderId:0}

                myPdfItem.url = listold[i]
                myPdfItem.id = MYId
                myPdfItem.orderId = $('#dataId').val();
                $('#myUpdataDivOld').prepend(`
				<div href="#" class="mybutton upload " myid="${myPdfItem.id+'-0'}" onclick="openPdf(${myPdfItem.id});" > 
					    <img class="upImg" src="/img/pdf.png">
						<span style=" color: #000;   text-align: center; ">
							${myPdfItem.name}</span>
						<input value="${myPdfItem.id}" class="layui-hide"> 
						<a href="#" onclick="remove(${myPdfItem.id},0);"> 
<!--						<img  class="closeUpload" src="/img/close.png" >	-->
						</a>
				</div>
				`)
                myPdfItem.id = MYId + '-0'
                // myPdf.push(myPdfItem)
                oldPdf.push(myPdfItem)
                ++MYId;
            }

            let listYi = $('#pdfListYi').val()
            listYi = listYi ? listYi.split(',') : []
            for (let i = 0; i < listYi.length; i++) {
                myPdfItem = {name: '文件' + (i + 1), url: '', id: '',contractType:$('#contractType').val(),orderId:0}

                myPdfItem.url = listYi[i]
                myPdfItem.id = MYId
                myPdfItem.orderId = $('#dataId').val();
                $('#myUpdataDivYi').prepend(`
				<div href="#" class="mybutton upload " myid="${myPdfItem.id+'-0'}" onclick="openPdf(${myPdfItem.id});" > 
					    <img class="upImg" src="/img/pdf.png">
						<span style=" color: #000;   text-align: center; ">
							${myPdfItem.name}</span>
						<input value="${myPdfItem.id}" class="layui-hide"> 
						<a href="#" onclick="remove(${myPdfItem.id},1);"> `+
                    ($('#type').val() == 'edit'? `<img  class="closeUpload" src="/img/close.png" >	`:'')+` </a></div>`)
                myPdfItem.id = MYId + '-0'
                if($('#type').val() == 'edit'){
                    myPdfYi.push(myPdfItem)
                }else{
                    oldPdf.push(myPdfItem)
                }
                ++MYId;
            }

            let listYiOld = $('#pdfListYiOld').val()
            listYiOld = listYiOld ? listYiOld.split(',') : []
            oldHT[1]=-1
            for (let i = 0; i < listYiOld.length; i++) {
                myPdfItem = {name: '文件' + (i + 1), url: '', id: '',contractType:$('#contractType').val(),orderId:0}

                myPdfItem.url = listYiOld[i]
                myPdfItem.id = MYId
                myPdfItem.orderId = $('#dataId').val();
                $('#myUpdataDivYiOld').prepend(`
				<div href="#" class="mybutton upload " myid="${myPdfItem.id+'-0'}" onclick="openPdf(${myPdfItem.id});" > 
					    <img class="upImg" src="/img/pdf.png">
						<span style=" color: #000;   text-align: center; ">
							${myPdfItem.name}</span>
						<input value="${myPdfItem.id}" class="layui-hide"> 
						<a href="#" onclick="remove(${myPdfItem.id},1);"> 
<!--						<img  class="closeUpload" src="/img/close.png" >	-->
						</a>
				</div>
				`)
                myPdfItem.id = MYId + '-0'
                // myPdfYi.push(myPdfItem)
                oldPdf.push(myPdfItem)
                ++MYId;
            }
        }

    }

    form.on('radio(demo-radio-filter)', function (data) {

        if (data?.elem?.value == '1') {
            $('#refuseReason').show()
        } else {
            $('#refuseReason').hide()
            $("textarea[name='refuseReason']").val('');
        }

    });
    let contractUpload=''
    contractUpload=upload.render({
        elem: '#contract'
        , url: '/common/sysFile/upload'
        , accept: 'file'
        , exts: 'pdf'
        , acceptMime: 'application/pdf'
        , before: function (obj) {
            //必须删除前面的用户合同
            if(oldHT[0]>0){
                layer.msg('请删除历史合同后，在传')
                contractUpload.config.elem.next()[0].value = '';
                contractUpload.config.elem.next()[0].outerHTML = contractUpload.config.elem.next()[0].outerHTML;
                contractUpload.reload(); // 重新加载upload实例
                return false;
            }
            if(myPdf.length>=3){
                layer.msg('上传已达上限，请删除在传')
                contractUpload.config.elem.next()[0].value = '';
                contractUpload.config.elem.next()[0].outerHTML = contractUpload.config.elem.next()[0].outerHTML;
                contractUpload.reload(); // 重新加载upload实例
                return false;
            }
            var files = this.files = obj.pushFile();  //将每次选择的文件追加到文件队列
            for (var key in files) {
                if (!myPdf.find(item => item.id == key)) {
                    myPdfItem = {name: '', url: '', id: ''}
                    myPdfItem.name = files[key].name
                    myPdfItem.id = key
                }
            }
            //读取本地文件
            obj.preview(function (index, file, result) {
                console.log(file.Name);
            });
            loading = layer.load({
                type: 3,
                content: '加载中...',
            });//在post之前定义loading
        }
        , done: function (res, index) {
            layer.close(loading);
            if (res.code == 0) {
                if(myPdf.length<3){
                    layer.msg('上传成功');
                    myPdfItem.url = res.data
                    myPdf.push(myPdfItem)
                    delete this.files[index]
                    $('#myUpdataDiv').prepend(`
				<div href="#" class="mybutton upload " myid="${myPdfItem.id}" onclick="openPdf(${myPdfItem.id});" > 
					    <img class="upImg" src="/img/pdf.png">
						<span style=" color: #000;   text-align: center; ">
							${myPdfItem.name}</span>
						<input value="${myPdfItem.id}" class="layui-hide">
						<a href="#" onclick="remove(${myPdfItem.id},0);"> 
						<img  class="closeUpload" src="/img/close.png" >	
						</a>
				</div>
				`)
                }else {
                    layer.msg('上传已达上限，请删除在传')
                }
            } else {
                layer.msg('上传失败,请检查');
            }

        }
    })

    let contractUploadYi=''
    contractUploadYi=upload.render({
        elem: '#contractYi'
        , url: '/common/sysFile/upload'
        , accept: 'file'
        , exts: 'pdf'
        , acceptMime: 'application/pdf'
        , before: function (obj) {
            //必须删除前面的用户合同
            if(oldHT[1]>0){
                layer.msg('请删除历史合同后，在传')
                contractUploadYi.config.elem.next()[0].value = '';
                contractUploadYi.config.elem.next()[0].outerHTML = contractUploadYi.config.elem.next()[0].outerHTML;
                contractUploadYi.reload(); // 重新加载upload实例
                return false;
            }
            if(myPdfYi.length>=3){
                layer.msg('上传已达上限，请删除在传')
                contractUploadYi.config.elem.next()[0].value = '';
                contractUploadYi.config.elem.next()[0].outerHTML = contractUploadYi.config.elem.next()[0].outerHTML;
                contractUploadYi.reload(); // 重新加载upload实例
                return false;
            }
            var files = this.files = obj.pushFile();  //将每次选择的文件追加到文件队列
            for (var key in files) {
                if (!myPdfYi.find(item => item.id == key)) {
                    myPdfItem = {name: '', url: '', id: ''}
                    myPdfItem.name = files[key].name
                    myPdfItem.id = key
                }
            }
            //读取本地文件
            obj.preview(function (index, file, result) {
                console.log(file.Name);
            });
            loading = layer.load({
                type: 3,
                content: '加载中...',
            });//在post之前定义loading
        }
        , done: function (res, index) {
            layer.close(loading);
            if (res.code == 0) {

                if(myPdfYi.length<3){
                    layer.msg('上传成功');
                    myPdfItem.url = res.data
                    myPdfYi.push(myPdfItem)
                    delete this.files[index]
                    $('#myUpdataDivYi').prepend(`
				<div href="#" class="mybutton upload " myid="${myPdfItem.id}" onclick="openPdf(${myPdfItem.id});" > 
					    <img class="upImg" src="/img/pdf.png">
						<span style=" color: #000;   text-align: center; ">
							${myPdfItem.name}</span>
						<input value="${myPdfItem.id}" class="layui-hide">
						<a href="#" onclick="remove(${myPdfItem.id},1);"> 
						   <img  class="closeUpload" src="/img/close.png" >	
						</a>
				</div>
				`)
                }else {
                    layer.msg('上传已达上限，请删除在传')
                }
            } else {
                layer.msg('上传失败,请检查');
            }

        }
    })

    //提交事件
    form.on('submit(submit)', function (data) {

        if ($('#orderType').val() == 1) {
            console.log('保洁详情')
            if ($('#status').val() == 0) {
                //修改
                console.log('修改',)
                if('edit'==$('#type').val()){
                    AjaxPost("/jzweb/jazUserOrder/update", {
                        id: $('#dataId').val(),
                        signingId: data.field.mySelect,
                    }).then(res => {
                        parent.layer.msg("操作成功");
                        parent.load();
                        var index = parent.layer.getFrameIndex(window.name); // 获取窗口索引
                        parent.layer.close(index);
                    }).catch(e => {
                        layer.msg(e.msg);
                    })
                }else{
                    parent.load();
                    var index = parent.layer.getFrameIndex(window.name); // 获取窗口索引
                    parent.layer.close(index);
                }
                return false
            }
            if ($('#status').val() == 1 && $('#afterPictureList').val()>0) {
                let zt = data.field.auditResult
                if (!zt) {
                    layer.msg('请先进行审核')
                }
                if( data.field.auditResult+""=="1" &&  data.field.refuseReason==''){
                    layer.msg("请输入拒绝原因")
                    return false
                }
                //审核
                AjaxPost("/jzweb/jazUserOrder/updateAuditResult", {
                    id: $('#dataId').val(),
                    auditResult: zt,
                    rejectReasion: data.field.refuseReason
                }).then(res => {
                    parent.layer.msg("操作成功");
                    parent.load();
                    var index = parent.layer.getFrameIndex(window.name); // 获取窗口索引
                    parent.layer.close(index);
                }).catch(e => {
                    layer.msg(e.msg);
                })

                return false
            }

            //待开始，进行中，已取消
            parent.load();
            var index = parent.layer.getFrameIndex(window.name); // 获取窗口索引
            parent.layer.close(index);
            return false
        }
        if ($('#orderType').val() == 2) {
            console.log('阿姨详情',data.field)
           if($('#type').val()=='edit' || $('#type').val()=='transferor'||$('#type').val()=='renew'){
               if (myPdf.length == 0) {
                   layer.msg('请上传用户合同pdf')
                   return false
               }
               if(oldHT[0]>0){
                   layer.msg('请上传新的用户合同pdf')
                   return false;
               }
               if (myPdfYi.length == 0) {
                   layer.msg('请上传阿姨合同pdf')
                   return false
               }
               if(oldHT[1]>0){
                   layer.msg('请上传新的阿姨合同pdf')
                   return false;
               }
               let myParams=data.field
               //订单周期
               myParams.startTime=myParams.myLaydate.split(' - ')[0]
               myParams.endTime=myParams.myLaydate.split(' - ')[1]
               delete myParams.myLaydate
               //合同
               myParams.contractNamePath = ''
               myPdf.forEach(item => {
                   myParams.contractNamePath += item.url + ','
               })
               myParams.contractNamePath=myParams.contractNamePath.substring(0,myParams.contractNamePath.length-1)
               myParams.contractNameYiPath = ''
               myPdfYi.forEach(item => {
                   myParams.contractNameYiPath += item.url + ','
               })
               myParams.contractNameYiPath=myParams.contractNameYiPath.substring(0,myParams.contractNameYiPath.length-1)

               delete myParams.file
               myParams.id=$('#dataId').val()
               myParams.signingId= $('#signingId').val()
               console.log('阿姨详情',myParams)
                if($('#type').val()=='renew'){
                    AjaxPost("/jzweb/jazUserOrder/orderRenew", myParams).then(res => {
                        parent.layer.msg("操作成功");
                        parent.load();
                        var index = parent.layer.getFrameIndex(window.name); // 获取窗口索引
                        parent.layer.close(index);
                    }).catch(e => {
                        layer.msg(e.msg);
                    })
                    return false
                }
                if($('#type').val()=='transferor'){
                    //转让
                    //设置名字
                    let item = myDataList.find((itemdata) => itemdata.sysUserid == myParams.names)
                    myParams.names=item.name
                    AjaxPost("/jzweb/jazUserOrder/serviceTransfer", myParams).then(res => {
                        parent.layer.msg("操作成功");
                        parent.load();
                        var index = parent.layer.getFrameIndex(window.name); // 获取窗口索引
                        parent.layer.close(index);
                    }).catch(e => {
                        layer.msg(e.msg);
                    })
                    return false
                }
                let item = myDataList.find((itemdata) => itemdata.sysUserid == myParams.names)
                myParams.names=item.name
                AjaxPost("/jzweb/jazUserOrder/updateUserOrderAunt", myParams).then(res => {
                   parent.layer.msg("操作成功");
                   parent.load();
                   var index = parent.layer.getFrameIndex(window.name); // 获取窗口索引
                   parent.layer.close(index);
               }).catch(e => {
                   layer.msg(e.msg);
               })

               return false
           }
            parent.load();
            var index = parent.layer.getFrameIndex(window.name); // 获取窗口索引
            parent.layer.close(index);
            return false;
        }


        console.log('data', data.field)
        if ($('#type').val() == 'info') {
            parent.load();
            var index = parent.layer.getFrameIndex(window.name); // 获取窗口索引
            parent.layer.close(index);
            return false
        }
        if (myPdf.length == 0) {
            layer.msg('请上传用户合同pdf')
            return false
        }
        if (myPdfYi.length == 0) {
            layer.msg('请上传阿姨合同pdf')
            return false
        }

        let mydata = data.field
        if (mydata.signedUserId == '') {
            layer.msg('请选择签约方')
            return false
        }
        mydata.pdfPath = ''
        myPdf.forEach(item => {
            mydata.pdfPath += item.url + ','
        })
        mydata.contractNameYiPath = ''
        myPdfYi.forEach(item => {
            mydata.contractNameYiPath += item.url + ','
        })
        delete mydata.file
        mydata.pdfPath = mydata.pdfPath.substring(0, mydata.pdfPath.length - 1)
        mydata.contractNameYiPath = mydata.contractNameYiPath.substring(0, mydata.contractNameYiPath.length - 1)
        AjaxPost(prefix + "/insertSysContract", mydata).then(res => {
            parent.layer.msg("操作成功");
            parent.load();
            var index = parent.layer.getFrameIndex(window.name); // 获取窗口索引
            parent.layer.close(index);
        }).catch(e => {
            layer.msg(e.msg);
        })

        return false;
    });


});